package com.fafa.pos.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.*;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import com.fafa.pos.R;
import com.fafa.pos.biz.ComplexBiz;
import com.fafa.pos.dao.*;
import com.fafa.pos.dao.impl.*;
import com.fafa.pos.pojo.Config;
import com.fafa.pos.pojo.UserInfo;
import com.fafa.pos.util.MyActivityManager;
import com.fafa.pos.util.SharedPreferencesHelper;
import com.fafa.pos.util.WebServiceUtil;
import com.fafa.pos.util.WebServiceValueCastUtil;
import com.fafa.pos.vo.CurUser;
import com.fafa.pos.vo.Status;
import com.fafa.pos.vo.WSResult;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends Activity{


    private SharedPreferencesHelper sharedPreferencesHelper;
    private String userCode;

    //DB相关
    private DBUtil dbUtil;
    private IUserInfoDao userInfoDao;
    private IConfigDao configDao;

    //View相关
    private EditText code;
    private EditText password;
    private Button submit;
    private TextView offLine_des;
    private ImageView offLine_img;
    private RelativeLayout progressBarCircularIndeterminate;
    private RelativeLayout offLine;
    private TextView systemSetting;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //加入退出管理
        MyActivityManager.getInstance().addActivity(this);
        //设置登录activity  为注销账户做准备
        MyActivityManager.getInstance().setLoginActivity(this);

        /*dbUtil = new DBUtil(getApplicationContext().getFilesDir().getAbsoluteFile()+"/pos.db");
        dbUtil.clear();*/




        initDB();
        initView();
        initEvent();

    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
        initEvent();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode==KeyEvent.KEYCODE_BACK){
            MyActivityManager.getInstance().exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化控件
     */
    private void initView(){

        sharedPreferencesHelper = new SharedPreferencesHelper(
                LoginActivity.this, "PosUserInfo");  //实例化sharedPreferencesHelper工具类
         userCode = sharedPreferencesHelper.getSharedPreference("userCode", "").toString().trim();//获取userCode

        code = (EditText) findViewById(R.id.code);
        password = (EditText) findViewById(R.id.password);
        submit = (Button) findViewById(R.id.submit);
        offLine_des = (TextView) findViewById(R.id.offLine_des);
        offLine_img = (ImageView) findViewById(R.id.offLine_img);
        offLine = (RelativeLayout) findViewById(R.id.offLine);
        systemSetting = (TextView) findViewById(R.id.systemSetting);
        progressBarCircularIndeterminate = (RelativeLayout) findViewById(R.id.loading);

//        if(CurUser.getUser().getCode()!=null){
//            code.setText(CurUser.getUser().getCode());
//            code.setSelection(code.getText().length());
//        }

        if(userCode!=null){
            code.setText(userCode);
            code.setSelection(code.getText().length());
        }
        if(Status.getStatus().isOffLine()){
            offLine_img.setBackgroundResource(R.drawable.right_active);
        }else{
            offLine_img.setBackgroundResource(R.drawable.right);
        }


    }

    /**
     * 初始化dao层实例
     */
    private void initDB(){
        dbUtil = new DBUtil(getApplicationContext().getFilesDir().getAbsoluteFile()+"/pos.db");
        userInfoDao = new UserInfoDaoImpl(dbUtil);
        configDao = new ConfigDaoImpl(dbUtil);

        //初始化配置文件
        Config config = configDao.getConfig();
        if(config.getProperties().get("serverIp")==null||"".equals(config.getProperties().get("serverIp").trim())){
            config.getProperties().put("serverIp","192.168.1.240:9191");
        }
        if(config.getProperties().get("webService")==null||"".equals(config.getProperties().get("webService").trim())){
            config.getProperties().put("webService","SodxV2.Web.Interface");
        }
        if(config.getProperties().get("posCode")==null||"".equals(config.getProperties().get("posCode").trim())){
            config.getProperties().put("posCode","1001");
        }
        if(config.getProperties().get("scanIntervalTime")==null||"".equals(config.getProperties().get("scanIntervalTime").trim())){
            config.getProperties().put("scanIntervalTime","10");
        }
        if(config.getProperties().get("defaultPrint")==null||"".equals(config.getProperties().get("defaultPrint").trim())){
            config.getProperties().put("defaultPrint","true");
        }
        configDao.saveConfig(config);


        config = configDao.getConfig();
    }

    /**
     * 控件绑定事件
     */
    private void initEvent(){

        //系统设置入口
        systemSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,SettingActivity.class);
                startActivity(intent);
            }
        });

        //登录时离线按钮点击事件
        View.OnClickListener doOffLine = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Status.getStatus().isOffLine()){
                    offLine_img.setImageResource(R.drawable.right);
                    Status.getStatus().setOffLine(false);
                }else{
                    offLine_img.setImageResource(R.drawable.right_active);
                    Status.getStatus().setOffLine(true);
                }
            }
        };
        offLine.setOnClickListener(doOffLine);

        //登录
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if(!Status.getStatus().isOffLine()){//在线登录
                    Map<String,Object> parameters = new HashMap<>();
                    parameters.put("userCode",code.getText().toString().trim());
                    parameters.put("passWord",password.getText().toString().trim());
                    Config config = configDao.getConfig();
                    parameters.put("posCode",config.getProperties().get("posCode"));
                    SoapObject so = WebServiceUtil.getResponse(config,"UserLogin",parameters,1000*15);

                    if(so!=null){
                        SoapPrimitive sp = (SoapPrimitive) so.getProperty("UserLoginResult");
                        WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                        if(wsResult.getResultCode()==0){

                            downloadHandler.sendEmptyMessage(3);

                            //保存当前登录用户的信息
                            CurUser user = CurUser.getUser();
                            user.setCode(code.getText().toString().trim());
                            user.setUserId(wsResult.getResultValues().get("USER_ID").toString());
                            user.setUserName(wsResult.getResultValues().get("USER_NAME").toString());

                            //SharedPreferences存储登录信息
                            sharedPreferencesHelper.put("userCode", code.getText().toString().trim());
                            sharedPreferencesHelper.put("userId", wsResult.getResultValues().get("USER_ID").toString());
                            sharedPreferencesHelper.put("userName", wsResult.getResultValues().get("USER_NAME").toString());


                            //下载基础数据
                            downloadData();
                        }else{
                            Toast.makeText(LoginActivity.this,wsResult.getResultValues().get("message").toString(),Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(LoginActivity.this,"连接超时",Toast.LENGTH_SHORT).show();
                    }
                }else{//离线登录
                    UserInfo userInfo = userInfoDao.checkLoginUser(code.getText().toString().trim(),password.getText().toString().trim());
                    if(userInfo!=null){

                        CurUser user = CurUser.getUser();
                        user.setCode(code.getText().toString().trim());
                        user.setUserId(userInfo.getUserId());
                        user.setUserName(userInfo.getUserName());

                        //SharedPreferences存储登录信息
                        sharedPreferencesHelper.put("userCode", code.getText().toString().trim());
                        sharedPreferencesHelper.put("userId", userInfo.getUserId());
                        sharedPreferencesHelper.put("userName", userInfo.getUserName());

                        //跳转到主界面
                        Intent intent = new Intent(LoginActivity.this,BFMainActivity.class);
                        startActivity(intent);
                    }else{
                        Toast.makeText(LoginActivity.this,"查询提示:查无此用户或密码错误",Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
    }

    private Handler downloadHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 1:
                    toMain();
                    break;
                case 2:
                    loginError(msg.obj.toString());
                    break;
                case 3:
                    //确定按钮解除事件
                    submit.setOnClickListener(null);
                    progressBarCircularIndeterminate.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };
    private void downloadData(){

        Thread download = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean isSuccessful = true;
                ComplexBiz complexBiz1 = new ComplexBiz(dbUtil);
                String errorMessage = complexBiz1.downloadData();

                if(errorMessage!=null){//下载数据失败
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = errorMessage;
                    downloadHandler.sendMessage(msg);
                }else{//下载数据成功
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = null;
                    downloadHandler.sendMessage(msg);
                }
            }
        });
        download.start();
    }

    private void loginError(String errorMessage){

        initEvent();
        progressBarCircularIndeterminate.setVisibility(View.INVISIBLE);
        //提示错误
        TextView suggest = new TextView(LoginActivity.this);
        suggest.setText(errorMessage);
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setTitle("下载失败").setIcon(R.drawable.error_icon);
        builder.setView(suggest);
        builder.setPositiveButton("确认",null);
        builder.show();
    }

    private void toMain(){
        progressBarCircularIndeterminate.setVisibility(View.INVISIBLE);
        //跳转到主界面
        Intent intent = new Intent(LoginActivity.this,BFMainActivity.class);
        startActivity(intent);
        finish();
    }
}
